import { createRouter, createWebHashHistory } from 'vue-router';
import RouteConfig from './routeConfig';
import MainBox from '../views/MainBox.vue';
import store from '../store/index';

const routes = [
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录',
    },
    component: () => import('../views/Login.vue'),
  },
  {
    path: '/mainBox',
    name: 'mainBox',
    component: MainBox,
    meta: {
      title: '主页',
    },
  },
  // mainBox的嵌套路由，根据权限动态加入
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const routeConfig = () => {
  RouteConfig.forEach((v) => {
    router.addRoute('mainBox', v);
  });
  store.commit('changeGetRouter', true);
};

// 路由拦截
router.beforeEach((to, form, next) => {
  window.document.title = to.meta.title;
  if (to.name === 'login') {
    next();
  } else if (!localStorage.getItem('token')) {
    next({ path: 'login' });
  } else {
    // 是否第一次进入
    if (!store.state.isGetRouter) {
      routeConfig();
      next({ path: to.fullPath });
    } else {
      next();
    }
  }
});

export default router;
